package com.yonyou.brigade.third_parties.didi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.didi.dao.DidiInvoiceHistoryMapper;
import com.yonyou.brigade.third_parties.didi.model.DidiInvoiceHistory;
import com.yonyou.brigade.third_parties.didi.service.IDiDiInvoiceService;
import com.yonyou.brigade.third_parties.didi.service.IDidiInvoiceHistoryService;
import com.yonyou.brigade.third_parties.didi.util.DiDiConstants;
import com.yonyou.brigade.third_parties.didi.util.EmailUtil;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 滴滴开票历史 服务实现类
 * </p>
 *
 * @author kangfw5@yonyou.com
 * @since 2019-07-10
 */
@Service
@Slf4j
public class DidiInvoiceHistoryServiceImpl extends ServiceImpl<DidiInvoiceHistoryMapper, DidiInvoiceHistory> implements IDidiInvoiceHistoryService {
    @Autowired
    private IUserCenterService userCenterService;
    @Autowired
    private IDiDiInvoiceService diDiInvoiceService;

    @Autowired
    private EmailUtil emailUtil;

    @Override
    public Page queryInvoiceHistoryWithPage(Page<DidiInvoiceHistory> page, String tenantId, String phone) {
        UcUserDto userDto = userCenterService.getCompleteUcUserDtoByPhone(phone, tenantId);
        if (userDto == null) {
            throw new BusinessException("用户中心不存在该用户");
        }
        Wrapper<DidiInvoiceHistory> wrapper = new EntityWrapper<>();
        wrapper.eq(DidiInvoiceHistory.TENANT, tenantId).eq(DidiInvoiceHistory.USER_ID, userDto.getUserId()).eq(DidiInvoiceHistory.SUCCESS, 1);

        /*//查询滴滴开票历史
        InvoiceQueryParam invoiceQueryParam = new InvoiceQueryParam();
        JSONObject jsonObject = diDiInvoiceService.queryInvoice(tenantId, null, invoiceQueryParam);*/

        return this.selectPage(page, wrapper);
    }

    @Override
    public String getInvoiceAddress(String tenantId, String phone, String invoiceId) {
        return getAppendixAdress(tenantId, invoiceId, DiDiConstants.DOWNLOAD_TYPE_INVOICE);
    }

    @Override
    public String getItineraryAddress(String tenantId, String phone, String invoiceId) {
        return getAppendixAdress(tenantId, invoiceId, DiDiConstants.DOWNLOAD_TYPE_ITINERARY);
    }

    @Override
    public Map<String, String> reSendEmail(String tenantId, String phone, String invoiceId) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, String> addrMap = getAppendixAdresses(tenantId, invoiceId, new HashMap<>());
        Email email = new Email();
        email.setEmail(new String[]{addrMap.get("receiverEmail")});
        email.setSubject("滴滴出行电子发票及行程报销单");
        String itineraryString = addrMap.get(DiDiConstants.DOWNLOAD_TYPE_ITINERARY);
        String invoiceString = addrMap.get(DiDiConstants.DOWNLOAD_TYPE_INVOICE);

        try {
            emailUtil.sendAttachment(email,itineraryString,invoiceString);
        }catch (Exception e){
            e.printStackTrace();
            log.error("滴滴重新发送电子发票异常->" + e.getMessage());
            resultMap.put("success", "false");
            resultMap.put("msg", "滴滴重新发送电子发票异常");
            return resultMap;
        }
        resultMap.put("success","true");
        resultMap.put("msg", "滴滴出行行程单及电子发票已发送");
        return resultMap;
    }

    /**
     * 获取滴滴发票或行程单地址
     *
     * @param tenantId  租户ID
     * @param invoiceId 发票ID
     * @param type      类型
     * @return
     */
    private String getAppendixAdress(String tenantId, String invoiceId, String type) {
        Map<String,String> addrMap = getAppendixAdresses(tenantId, invoiceId, new HashMap<>());

        return addrMap.get(type);
    }

    /**
     * 获取滴滴发票和行程单地址
     * @param tenantId
     * @param invoiceId
     * @param addressMap
     * @return
     */
    private Map<String,String> getAppendixAdresses(String tenantId, String invoiceId, Map<String,String> addressMap){

        Wrapper<DidiInvoiceHistory> wrapper = new EntityWrapper<>();
        wrapper.eq(DidiInvoiceHistory.INVOICE_ID, invoiceId);
        List<DidiInvoiceHistory> historyList = this.selectList(wrapper);
        if (CollectionUtils.isEmpty(historyList)) {
            throw new BusinessException("未找到对应开票历史");
        }

        DidiInvoiceHistory didiInvoiceHistory = historyList.get(0);
        if (StringUtils.isEmpty(didiInvoiceHistory.getInvoiceAddress()) || StringUtils.isEmpty(didiInvoiceHistory.getItineraryAddress())) {
            try {
                List<String> addressList = diDiInvoiceService.downloadInvoice(tenantId, invoiceId);
                List<String> invoiceAddressList = new ArrayList<>();
                List<String> itineraryAddressList = new ArrayList<>();
                for (String address : addressList) {
                    if (URLDecoder.decode(address).contains(DiDiConstants.DOWNLOAD_TYPE_INVOICE)) {
                        invoiceAddressList.add(address);
                    } else if (URLDecoder.decode(address).contains(DiDiConstants.DOWNLOAD_TYPE_ITINERARY)) {
                        itineraryAddressList.add(address);
                    }
                }
                String invoiceAddr = String.join(",", invoiceAddressList);
                didiInvoiceHistory.setInvoiceAddress(invoiceAddr);
                String itineraryAddr = String.join(",", itineraryAddressList);
                didiInvoiceHistory.setItineraryAddress(itineraryAddr);
                this.updateById(didiInvoiceHistory);

            } catch (Exception e) {
                throw new CustomException("滴滴电子发票/行程单下载失败" + e.getMessage());
            }
        }
        addressMap.put(DiDiConstants.DOWNLOAD_TYPE_INVOICE, didiInvoiceHistory.getInvoiceAddress());
        addressMap.put(DiDiConstants.DOWNLOAD_TYPE_ITINERARY, didiInvoiceHistory.getItineraryAddress());

        addressMap.put("receiverEmail", didiInvoiceHistory.getReceiverEmail());
        return addressMap;
    }
}
